<script setup lang='ts'>
import { computed, ref, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useProducts } from '../../composables/useProducts'
import { useCart } from '../../composables/useCart'
import { ElMessage } from 'element-plus'
import { useFavorites } from '../../composables/useFavorites'
import { useComments } from '../../composables/useComments'
import { fetchComments, addComment as addCommentApi } from '@/api/comment'
import { useAuthStore } from '../../stores/auth'

const route = useRoute()
const router = useRouter()
const { products, loading } = useProducts()
const { addToCart } = useCart()
const { isFav, toggle } = useFavorites()
const auth = useAuthStore()

const product = computed(() => {
  const id = String(route.params.id || '')
  return products.value.find(p => String(p.id) === id)
})

function handleAdd() {
  if (product.value) {
    if (!auth.isLoggedIn) {
      ElMessage.warning('请先登录')
      router.push('/')
      return
    }
    addToCart(product.value, 1)
    ElMessage.success('已加入购物车')
  }
}

const buyLoading = ref(false)
const favLoading = ref(false)
const quantity = ref(1)

async function handleBuyNow() {
  if (!product.value) return
  buyLoading.value = true
  try {
    if (!auth.isLoggedIn) {
      ElMessage.warning('请先登录')
      router.push('/')
      return
    }
    addToCart(product.value, quantity.value)
    ElMessage.success('已加入购物车，前往结算')
    // 此处可跳转结算页
  } finally {
    buyLoading.value = false
  }
}

async function handleToggleFav() {
  if (!product.value) return
  favLoading.value = true
  try {
    if (!auth.isLoggedIn) {
      ElMessage.warning('请先登录')
      router.push('/')
      return
    }
    const state = toggle(product.value.id)
    ElMessage.success(state ? '已收藏' : '已取消收藏')
  } finally {
    favLoading.value = false
  }
}

const pid = computed(() => String(route.params.id || ''))
const { list: comments, add: addComment } = useComments(pid.value)
const author = ref('游客')
const content = ref('')
const rating = ref(5)
const commentsLoading = ref(false)

// 加载服务端评论
async function loadServerComments() {
  if (!auth.isLoggedIn) return
  commentsLoading.value = true
  try {
    const res = await fetchComments({ goodId: Number(pid.value), current: 1, size: 50 })
    const records = res?.data?.data?.records || []
    // 将服务端评论添加到本地评论列表
    records.forEach((comment: any) => {
      addComment(comment.content, comment.rating || 5)
    })
  } catch (e) {
    console.error('加载评论失败:', e)
  } finally {
    commentsLoading.value = false
  }
}

async function submitComment() {
  const text = content.value.trim()
  if (!text) return
  
  if (!auth.isLoggedIn) {
    ElMessage.warning('请先登录')
    router.push('/')
    return
  }
  
  try {
    // 提交到服务端
    await addCommentApi({
      goodId: Number(pid.value),
      content: text,
      rating: rating.value,
      userId: 1 // 临时用户ID，实际应从登录状态获取
    })
    
    // 添加到本地
    addComment(author.value || '游客', text)
    content.value = ''
    rating.value = 5
    ElMessage.success('评论成功')
  } catch (e: any) {
    ElMessage.error(e?.message || '评论失败')
  }
}

onMounted(() => {
  loadServerComments()
})
</script>

<template>
  <div class="detail-page">
    <el-skeleton :loading="loading" animated :rows="6">
      <template #template>
        <el-skeleton-item variant="image" style="width: 420px; height: 420px;" />
      </template>
      <template #default>
        <el-row :gutter="24" v-if="product">
          <el-col :span="10">
            <img :src="product.imgs" class="product-img" />
          </el-col>
          <el-col :span="14">
            <h2 class="title">{{ product.name }}</h2>
            <p class="price">￥{{ product.saleMoney }}</p>
            <p class="desc">{{ product.description }}</p>
            <div class="actions">
              <div class="qty">
                <span>数量</span>
                <el-input-number v-model="quantity" :min="1" />
              </div>
              <div class="btns">
                <el-button type="danger" size="large" :loading="buyLoading" @click="handleBuyNow">立即购买</el-button>
                <el-button size="large" :loading="favLoading" :type="isFav(product.id) ? 'warning' : 'default'" @click="handleToggleFav">{{ isFav(product.id) ? '取消收藏' : '收藏' }}</el-button>
                <el-button type="primary" size="large" @click="handleAdd">加入购物车</el-button>
              </div>
            </div>
            <div class="sub">
              温馨提示：支持7天无理由退货
            </div>
          </el-col>
        </el-row>
        <div v-else class="empty">未找到该商品</div>
      </template>
    </el-skeleton>

    <div class="detail-sections">
      <el-card class="comment-card">
        <template #header>
          <div class="card-header">商品评论</div>
        </template>
        <div class="comment-form">
          <el-input v-model="author" placeholder="昵称（可选）" style="max-width: 220px" />
          <div class="rating-section">
            <span>评分：</span>
            <el-rate v-model="rating" :max="5" show-text />
          </div>
          <el-input v-model="content" type="textarea" :autosize="{ minRows: 3, maxRows: 6 }" placeholder="说点什么..." />
          <div class="comment-actions">
            <el-button type="primary" @click="submitComment">发表</el-button>
          </div>
        </div>
        <el-empty description="暂无评论" v-if="!comments.length" />
        <div v-else class="comment-list">
          <el-timeline>
            <el-timeline-item v-for="c in comments" :key="c.id" :timestamp="new Date(c.createdAt).toLocaleString()">
              <div class="c-author">{{ c.author }}</div>
              <div class="c-content">{{ c.content }}</div>
            </el-timeline-item>
          </el-timeline>
        </div>
      </el-card>
    </div>
  </div>
  
</template>

<style scoped>
.detail-page{
  width: 97.5%;
  margin: 16px auto;
  background: #fff;
  border-radius: 12px;
  padding: 20px;
}
.product-img{
  width: 100%;
  height: 420px;
  object-fit: cover;
  border-radius: 8px;
}
.title{ margin: 8px 0 4px; font-size: 24px; }
.price{ color: #f56c6c; font-size: 20px; margin: 6px 0; }
.desc{ color: #666; line-height: 1.6; margin: 8px 0 16px; }
.actions{ margin: 8px 0 12px; }
.actions .qty{ display: flex; align-items: center; gap: 10px; margin-bottom: 10px; }
.actions .btns{ display: flex; gap: 12px; flex-wrap: wrap; }
.sub{ color: #909399; font-size: 12px; }
.empty{ padding: 40px; color: #999; text-align: center; }

.detail-sections{ margin-top: 16px; }
.comment-card{ border-radius: 12px; }
.card-header{ font-weight: 700; }
.c-author{ font-weight: 600; margin-bottom: 4px; }
.c-content{ color: #606266; white-space: pre-wrap; }
.comment-form{ display: flex; flex-direction: column; gap: 10px; margin-bottom: 12px; }
.rating-section{ display: flex; align-items: center; gap: 8px; }
.comment-actions{ display: flex; justify-content: flex-end; }
.comment-list{ margin-top: 8px; }
</style>

